import { history } from 'umi'
const { pathToRegexp } = require("path-to-regexp")
import api from 'api'
import store from 'store'
const { loginUser,loginConfig } = api
import modelExtend from 'dva-model-extend'
import { model } from 'utils/model'

export default modelExtend(model, {
  namespace: 'demo',

  state: {
    config: {

    },
    message: null
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/demo').exec(location.pathname)) {

        }
      })
    },
  },
  effects: {
    *queryLoginConfig({payload}, {put,call, select}) {
      const data = yield  call(loginConfig, {})
      if(data.success) {
        yield  put({type: 'updateState', payload: {config: data.payload}})
      }
    },
    *login({ payload }, { put, call, select }) {
      yield put({type: 'updateState', payload: { message: "" }})
      const data = yield call(loginUser, payload)
      const { locationQuery } = yield select(_ => _.app)
      //保证http状态正常， 且业务api返回状态也正常
      if (data.success && data.code == 2000) {
        store.set("token", data.payload.token)
        const { from } = locationQuery
        yield put({ type: 'app/query' })
        if (!pathToRegexp('/login').exec(from)) {
          if (['', '/'].includes(from)) history.push('/dashboard')
          else history.push(from)
        } else {
          history.push('/dashboard')
        }
      } else {
        yield put({type: 'updateState', payload: { message: "登录失败，请重新登录" }})
      }
    },
  },
})
